package com.test.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.test.dao.BorrowDao;
import com.test.entity.Book;
import com.test.entity.Borrow;
import com.test.entity.User;
import com.test.entity.UserBorrowDetail;
import com.test.service.client.UserClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.stream.Collectors;

@Service("borrowService")
public class BorrowServiceImpl {
    @Autowired
    private BorrowDao borrowDao;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private UserClient userClient;

    public UserBorrowDetail getUserBorrowDetailByUid(int uid) {
        //User user = restTemplate.getForObject("http://userservice/user/" + uid, User.class);
        User user = userClient.getUserById(uid);
        List<Borrow> borrows = borrowDao.selectList(new LambdaQueryWrapper<Borrow>().eq(Borrow::getUid, uid));
        List<Book> books = borrows.stream()
                .map(borrow -> restTemplate.getForObject("http://bookservice/book/" + borrow.getBid(), Book.class))
                .collect(Collectors.toList());

        return new UserBorrowDetail(user, books);

    }
}
